package com.ndood.admin.repository.operator.pay_config.app.manager;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Repository;

import com.ndood.admin.core.jpa.entitymanager.EntityManagerModel;
import com.ndood.admin.pojo.operator.pay_config.app.dto.AppDto;

/**
 * 系统日志持久化管理类
 */
@Repository
@SuppressWarnings("unchecked")
public class AppRepositoryManager {
	
	@Autowired
	@PersistenceContext
	private EntityManager em;
	
	/**
	 * 查询出日志分页信息
	 */
	public Page<AppDto> pageAppList(String keywords, Integer pageNo, Integer pageSize) {

		// Step1: 动态拼接jpql
		EntityManagerModel model = EntityManagerModel.newModel();
		model.plusSQL("AND 1=1 ");
		if(!StringUtils.isBlank(keywords)) {
			model.plusSQL("AND s.name LIKE :name ").plusParam("name", "%"+keywords+"%");
		}
		
		// Step2: 获取list
		Query query = em.createQuery("SELECT new com.ndood.admin.pojo.operator.pay_config.app.dto.AppDto(s.id, s.appNo, s.name, s.limit, s.status, s.sort, s.createTime, s.updateTime ) "
				+ "FROM AppPo s "
				+ "WHERE 1 = 1 " + model.getSQLPlus()
				+ "ORDER BY s.sort DESC ");
		
		model.setQueryParam(query);
		query.setFirstResult(pageNo * pageSize).setMaxResults(pageSize);
		query.setHint("org.hibernate.cacheable", true);
		List<AppDto> resultList = query.getResultList();
		
		// Step3: 获取count
		Query queryCount = em.createQuery("SELECT COUNT(0) "
				+ "FROM AppPo s "
				+ "WHERE 1 = 1 " + model.getSQLPlus());

		model.setQueryParam(queryCount);
		queryCount.setHint("org.hibernate.cacheable", true);
		Long count = (Long)queryCount.getSingleResult();
		
		// Step4: 封装page
		Page<AppDto> page = new PageImpl<>(resultList, PageRequest.of(pageNo, pageSize), count);
		return page;
	
	}
	
}
